package com.jd.sentinelspringboot.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.jd.sentinelspringboot.service.FlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelController {

    @Autowired
    private FlowService flowService;

    @RequestMapping("/test1")
    public void test() throws InterruptedException {
        //2、定义资源
            Entry entry=null;
            try {
                //2。1 定义资源名称
                entry= SphU.entry("HelloWorld");
                //2.2 执行资源逻辑代码
                System.out.println("HelloWorld.main访问数据库");
                System.out.println("HelloWorld.main访问redis");
                System.out.println("HelloWorld.main数据库持久化操作");
                Thread.sleep(20);
            }catch (BlockException e){
                System.err.println("要访问的资源的被流控了，执行流控逻辑");
            }finally {
                if (entry != null) {
                    entry.exit();
                }
            }
    }



    @RequestMapping("/test2")
    public void test2() throws InterruptedException, BlockException {
        //2、定义资源
        Entry entry=null;
        try {
            //2。1 定义资源名称
            entry= SphU.entry("com.jd.sentinelspringboot.controller.TestController:test2");
            //2.2 执行资源逻辑代码
            System.out.println("HelloWorld.main访问数据库");
            System.out.println("HelloWorld.main访问redis");
            System.out.println("HelloWorld.main数据库持久化操作");
            Thread.sleep(20);
        }catch (DegradeException e){
            System.err.println("要访问的资源的被降级，执行降级");
        }finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }



    @RequestMapping("/test3")
    public String test3()  {
      return flowService.test();
    }
}
